<?php
namespace PsiFramework\Applications\AlloMediaUser\Classes\Actions;

use PsiFramework\Classes\Exceptions\SecurityException;

use \PsiFramework\Classes\Util\Parameters\Action\ActionParameters;
use \PsiFramework\Classes\Factory\DAOFactory;
use \PsiFramework\Classes\Actions\AbstractAction;
use \PsiFramework\Applications\AlloMediaPortal\Classes\DAO\AlloMediaEntryDAO;

/**
 * PsiFramework
 * Php Simple Framework
 *
 * @author Rémi San
 * @version beta
 */

/**
 * Classe d'action du preview
 *
 * @package Actions.Pages
 */
class PreviewAction extends AbstractAction
{

    public function __construct(ActionParameters $actionParameters)
    {
        parent::__construct($actionParameters);
    }

    /**
     * The main function of the method which is called every time
     * an action is created by the front controller.
     *
     */
    public function execute()
    {
        parent::execute();

        $entryId = $this->_request->getParameter('entry_id');
        $entry = null ;

        if (!isNullOrEmptyString($entryId)) {
            $entryDao = DAOFactory::getDAO('AlloMediaEntry');
            $entry = $entryDao->retrieveByPk($entryId);
            if (is_null($entry)) {
                throw new \Exception("Impossible de récupérer l'entrée !");
            }
        } else {
            $entry = $this->_session->get('entry');
            if (!is_null($entry) && $entry->getUser()->getId() != $this->_user->getId()) {
                $entry = null;
            }
        }
        
        if (is_null($entry)) {
            throw new SecurityException('You can\'t access this !');
        }
        
        $exemple = !is_null($this->_request->getParameter('example'));
        if ($exemple) {
            $entry = $entry->getCategory()->getExempleEntry();
        }
        
        $doc = new \DOMDocument('1.0', 'UTF-8');
        $doc->formatOutput = true;
        $entryXml = AlloMediaEntryDAO::getAsXml($entry, null, $doc);
        $doc->appendChild($entryXml);
        
        $this->_response->setAttribute("htmlResponse", $doc->saveXML());

        $this->findForward('success');
    }
}
